<?php
/**
 * 订单
 * User:zhan
 * Date: 2017/9/29 9:00
 *
 */

namespace app\admin\Controller;
use app\api\controller\Msn;
use app\api\logic\Pay;
use EasyWeChat\Foundation\Application;

use phpDocumentor\Reflection\DocBlock\Tags\Var_;
use think\Db;
use think\Request;
use think\Session;

class Order extends Common{
	
	/*
	*	构造函数
	*/
	function __construct(){
		parent::__construct();

	}
	/**
	 * 列表
	 */
	public function index(){
		$order = db('order');
		$where=array();
		if(input('status')!=''){
			$where['o.status']=input('status');
		}
		if(input('type')!=''){
			$where['o.type']=input('type');
		}
		$start_date=input('start_date');
		$end_date=input('end_date');
		if(input('keyword')!=''){
			$where['o.order_sn|m.mobile|m.nickname']=array('like','%'.input('keyword').'%');
		}
		if($start_date){
			$where['o.create_time']=array('gt',strtotime($start_date));
		}
		if($end_date){
			$where['o.create_time']=array('lt',strtotime($end_date));
		}
		if($start_date && $end_date){
			$where['o.create_time']=array('between',[strtotime($start_date),strtotime($end_date)]);
		}
		if(input("export")){
			$this->export($where);exit;
		}
		$list = $order->alias("o")
				->field("o.*,m.nickname,m.mobile as tell")
				->join("member m","m.id=o.uid")
				->where($where)
				->order("o.id desc")
				->paginate(10);
		$count = $order->alias("o")
				->field("o.*,m.nickname,m.mobile as tell")
				->join("member m","m.id=o.uid")
				->where($where)
				->order("o.id desc")
				->count(10);
		$money = $order->alias("o")
				->field("o.*,m.nickname,m.mobile as tell")
				->join("member m","m.id=o.uid")
				->where($where)
				->sum("price");
		$this -> assign("count",$count);
		$this -> assign("money",number_format($money,2));
		$this -> assign("list",$list);
		$this -> assign("type",input('type'));
		$this -> assign("status",input('status'));
		$this -> assign("end_date",$end_date);
		$this -> assign("start_date",$start_date);
		$this->assign('keyword',input('keyword'));
		return $this->fetch();
	}
	/**
	 * 详情
	 */
	public function detail(){
		Session::pull('co');
		$order = db('order');
		$where['o.id']=input('id');
		$list = $order->alias("o")
				->field("o.*,m.nickname,m.mobile")
				->join("member m","m.id=o.uid")
				->where($where)
				->find();
		$this -> assign("data",$list);
		return $this->fetch();
	}

	/**
	 * 退款列表
	 */
	public function refund(){
		$refund = db('order_refund');
		$where=array();
		$list = $refund->alias("o")
				->field("o.*,m.nickname,m.mobile")
				->join("member m","m.id=o.uid")
				->where($where)
				->order("id desc")
				->paginate(10);
		$this -> assign("list",$list);
		$this -> assign("type",input('type'));
		$this -> assign("status",input('status'));
		$this->assign('keyword',input('keyword'));
		return $this->fetch();
	}
	/**
	 * 审核退款
	 */
	public function pay(){
		$refund = db('order_refund');
		$where['r.id']=input('id');
		if(!in_array(input('status'),array(1,-1))) $this->error('参数有误');
		$list = $refund->alias("r")
				->field("r.*,m.nickname,m.openid,o.mobile,o.order_sn,o.price")
				->join("member m","m.id=r.uid")
				->join("order o","o.id=r.order_id")
				->where($where)
				->find();
		if(!$list) $this->error('记录不存在');
		if($list['status']!=0)  $this->error('非待审核状态');
		if(input('status')==-1){
			Db::startTrans();
			try{
			$de = $refund->alias("r")
					->field("r.*,m.nickname,m.mobile,m.openid")
					->join("member m","m.id=r.uid")
					->where($where)
					->update(array('r.status'=>-1));
				if(!$de) throw new \Exception('修改状态失败');
			$res=db("order")->where("id=".$list['order_id'])->update(array("status"=>1));
				if(!$res) throw new \Exception('更改订单状态失败');
				Db::commit();
			} catch (\Exception $e) {// 回滚事务
				Db::rollback();
				$this->error($e->getMessage());
			}
		}else{
			$order=db("order")->where("id=".$list['order_id'])->find();
			$options = [
				// 前面的appid什么的也得保留哦
					'app_id' =>config("wx.app_id"),
					'payment' => [
							'merchant_id'        => config("wx.mch_id"),
							'key'                => config("wx.key"),
							'cert_path'          =>EXTEND_PATH. 'cert\apiclient_cert.pem', // XXX: 绝对路径！！！！
							'key_path'           => EXTEND_PATH.'cert\apiclient_key.pem',      // XXX: 绝对路径！！！！
							'notify_url'         => '默认的订单回调地址',       // 你也可以在下单时单独设置来想覆盖它
					],
			];

			$app = new Application($options);
			$payment = $app->payment;
			$result = $payment->refund($order['order_sn'], $list['id'], $list['money']*100);
			if($result->result_code=='SUCCESS'){
				Db::startTrans();
				try{
					$de = $refund->alias("r")
							->field("r.*,m.nickname,m.mobile,m.openid")
							->join("member m","m.id=r.uid")
							->where($where)
							->update(array('r.status'=>1));
					if(!$de) throw new \Exception('修改状态失败');
					$res=db("order")->where("id=".$list['order_id'])->update(array("status"=>3));
					if(!$res) throw new \Exception('更改订单状态失败');
					if($de['credit']>0){ //退还积分
						db("member")->where("id=".$de['uid'])->setInc("integral",$de['credit']);
					}
					if($list['mobile']){
						$response = (new Msn())->sendSms(
								"新兴县七彩虹酒店", // 短信签名
								'SMS_117516543', // 短信模板编号
								$list['mobile'], // 短信接收者
								Array(  // 短信模板中字段的值
										"ordersn"=>$list['order_sn'],
										"price"=>$list['price'],
								),
								"123"
						);
					}

						$member=db("member")->where("id=".$order['uid'])->find();
						$app=(new Pay())->app();

					if($order['type']==0){
						$data=array(
								'touser' => $member['openid'],
								'template_id' => 'A6KOtuFCkEhu4rxb5in4zb2mDWs-abrPVyxh-_v6QA0',
								'url' =>  request()->domain().'/qchwap/#/orderDetail?id='.$list['id'],
								'data' => [
										'first' => '订单取消成功通知',
										'keyword1' => $order['order_sn'],
										'keyword2'=>'新兴县七彩虹酒店',
										'keyword3' =>date("Y-m-d H:i",$order['start_time']),
										'keyword4' =>date("Y-m-d H:i",$order['end_time']),
										'keyword5' =>$order['title'],
										'remark' => '如有疑问请致电酒店：0766-6636678'
								]
						);
					}else {
						$data = array(
								'touser' => $member['openid'],
								'template_id' => 'S-4KTDpxTe6EBMPu4I19EaRN8LqvQXJneXFu3nqnaNE',
								'url' => request()->domain() . '/qchwap/#/orderDetail?id=' . $order['id'],
								'data' => [
										'first' => '退票成功通知',
										'keyword1' => $order['order_sn'],
										'keyword2' => date("Y-m-d H:i"),
										'keyword3' => $order['title'],
										'keyword4' => '￥' . $order['price'],
										'keyword5' => $order['mobile'],

										'remark' => '如有疑问请致电酒店：0766-6636678'
								]
						);
					}
						$app->notice->send($data);

					Db::commit();
				} catch (\Exception $e) {// 回滚事务
					Db::rollback();
					$this->error($e->getMessage());
				}

				$this->success("操作成功",$_SERVER['HTTP_REFERER']);
			}
			if($result->result_code=='FAIL') $this->success($result->err_code_des);
			//if($result)
		}
	}

	public function finance(){

		//订单数量
		$order_db=db("order");
		$today['pay_time']=array('between',[strtotime(date("Y-m-d")),time()]);
		$today['status']=array('gt',0);
		$order['today']=$order_db->where($today)->count();
		$order['today_m']=number_format($order_db->where($today)->sum("price"),2);
		$yesterday['pay_time']=array('between',[strtotime(date("Y-m-d"))-24*60*60,strtotime(date("Y-m-d"))]);
		$yesterday['status']=array('gt',0);
		$order['yesterday']=$order_db->where($yesterday)->count();
		$order['yesterday_m']=number_format($order_db->where($yesterday)->sum("price"),2);
		$week['pay_time']=array('between',[strtotime(date("Y-m-d"))-6*24*60*60,time()]);
		$week['status']=array('gt',0);
		$order['week']=$order_db->where($week)->count();
		$order['week_m']=number_format($order_db->where($week)->sum("price"),2);
		$month['pay_time']=array('between',[strtotime(date("Y-m-d"))-29*24*60*60,time()]);
		$month['status']=array('gt',0);
		$order['month']=$order_db->where($month)->count();
		$order['month_m']=number_format($order_db->where($month)->sum("price"),2);
		$all['status']=array("gt",0);
		$order['all']=$order_db->where($all)->count();
		$order['all_m']=number_format($order_db->where($all)->sum("price"),2);
		$data=$this->get_week(time()-30*60*60*24);
		$this->assign("date",$data['str']);
		$this->assign("num",$data['num']);
		$this->assign("user",$data['user']);
		$this->assign("order",$order);
		return $this->fetch();
	}
	public function get_week($time, $format = "m-d") {
		$order_db=db("order");
		$str='[';
		$num='[';
		$user='[';
		for ($i=0;$i<30;$i++){
			$data[$i]['date'] = date($format,strtotime( '+'.$i+1 .' days',$time));
			$where['pay_time']=array("between",[strtotime(date('Y-m-d',strtotime( '+'.$i+1 .' days',$time))),strtotime(date('Y-m-d',strtotime( '+'.$i+1 .' days',$time)))+24*60*60]);
			$data[$i]['num']=$order_db->where($where)->count();
			$data[$i]['user']=floor(floatval($order_db->where($where)->sum("price"))*100)/100;
			if($i==0){
				$str.=   "'".$data[$i]['date']."'";
				$num.=   $data[$i]['num'];
				$user.=   $data[$i]['user'];
			}else{
				$str.=",". "'".$data[$i]['date']."'";
				$num.=",".$data[$i]['num'];
				$user.=",".$data[$i]['user'];
			}
		}
		$str.=']';
		$num.=']';
		$user.=']';
		ksort($data);
		return array('str'=>$str,'num'=>$num,'user'=>$user,);
	}

	/**
	 * 订单列表导出excel
	 */
	public function export($where)
	{

		$headArr = array("订单号","昵称","名称","状态","类型","开始时间","到期时间","价钱","下单时间","支付时间",
				'入住时间','完成时间','优惠券抵扣','积分抵扣','数量');
		//$where['status']=1;
		$list = db("order")->alias("o")
				->field("o.*,m.nickname")
				->join("member m","o.uid=m.id")
				->order("id desc")
				->where($where)
				->select();
		$data=array();
		foreach($list as $k => $v){
			$data[$k][] = $v['order_sn'];
			$data[$k][] = $v['nickname'];
			$data[$k][] = $v['title'];
			//0待支付，1已支付，2已完成，3已退款，-1已关闭，-2申请退款中
			switch($v['status']){
				case '0': $data[$k][]='待付款';break;
				case '1': $data[$k][]='已付款';break;
				case '2': $data[$k][]='已完成';break;
				case '-2': $data[$k][]='退款中';break;
				case '3': $data[$k][]='已退款';break;
				case '-1': $data[$k][]='已关闭';break;
			}
			//0订房1门票，2套餐
			switch($v['type']){
				case '0': $data[$k][]='房间';break;
				case '1': $data[$k][]='门票';break;
				case '2': $data[$k][]='套票';break;
			}
			$data[$k][] =!empty($v['start_time'])?date("Y-m-d H:i",$v['start_time']):'';
			$data[$k][] = !empty($v['end_time'])?date("Y-m-d H:i",$v['end_time']):'';
			$data[$k][] = $v['price'];
			$data[$k][] =!empty($v['create_time'])?date("Y-m-d H:i",$v['create_time']):'';
			$data[$k][] =!empty($v['pay_time'])?date("Y-m-d H:i",$v['pay_time']):'';
			$data[$k][] =!empty($v['check_time'])?date("Y-m-d H:i",$v['check_time']):'';
			$data[$k][] =!empty($v['finish_time'])?date("Y-m-d H:i",$v['finish_time']):'';
			$data[$k][] = $v['couponmoney'];
			$data[$k][] = $v['credit'];
			$data[$k][] = $v['count'];
		}
		$filename='订单列表';
		(new Export())->ImportExcel($filename,$headArr,$data);
	}
	public function  check(){
		$db_order = db('order');
		$where['delete']=0;
		$where['id']=input('id');
		$list=$db_order->where($where)->find();
		if(!$list) $this->error('订单不存在');
		if($list['status']!=1) $this->error('不是待入住状态');
		$res=$db_order->where($where)->update(array('ischeck'=>1,'check_time'=>NOW_TIME));
		if(!$res)  $this->error('系统繁忙，稍后再试');
		if($list['type']==0 && $list['ischeck']==0){
			$member=db("member")->where("id=".$list['uid'])->find();
			$app=(new Pay())->app();
			$data=array(
					'touser' => $member['openid'],
					'template_id' => 'n_d1ByJAoeVtky7YX9VzJTMY9Kf1K_-bxk87Szp35n4',
					'url' =>  request()->domain().'/qchwap/#/orderDetail?id='.$list['id'],
					'data' => [
							'first' => '入住成功',
							'hotelName' => '七彩虹酒店',
							'roomName'=>$list['title'],
							'date' => date("Y-m-d H:i"),
							'remark' => '如有疑问请致电酒店：0766-6636678'
					]
			);
			$app->notice->send($data);
		}
		$this->redirect($_SERVER['HTTP_REFERER']);
	}
}